<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\model;

use think\Model;
use app\admin\model\Config as ConfigModel;
use app\mill\model\Order as OrderModel;
use app\mill\model\Archives as ArchivesModel;
use app\mill\model\Audit as AuditModel;
use app\mill\model\Contract as ContractModel;
use think\Db;

/**
 * 账单表模型
 */
class Finance extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'mill_order_archives_initial_price';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    //计价状态
    public static $initial_price_status = [
        -1      => '未通过',
        0       => '待计价',
        1       => '待审核',
        2       => '已计价',
    ];

    /**
     * 价格正负显示
     * @param int $type 0:负 1:正
     * @param int $money 金额
     * @param bool $icon
     * @return int|string
     */
    public static function getMoneyStr($type = 1,$money = 0,$icon = false){
        if($type == 0)$money = '-'.abs($money);
        else $money = abs($money);

        if($icon && $money<0)$money = '<div style="color: #ff6b6b;">'.$money.'</div>';
        return $money;
    }
    // 表格制作
    //print 0:编辑模式 1:打印模式 2:导出模式
    public static function fromArchivesShow($order_id = 0){

        $where[] = ['a.order_id','=',$order_id];
        $join = [['mill_order o','a.order_id=o.id','left']];

        //单价设置

        $join[] = ['mill_client c','c.id=o.client_id','left'];
        $order = Db::name('mill_order_archives')
            ->alias('a')
            ->field('o.*,group_concat(o.archives_sn) as archives_sns,group_concat(o.batch) as batchs,c.company,c.mobile as c_mobile,SUM(a.number*a.weld) AS weld,SUM(a.number*a.slot) AS slot,SUM(a.number*a.torque) AS torque,SUM(a.number*a.bend) AS bend')
            ->join($join)
            ->where($where)
            ->order('a.order_id asc,a.sort asc')
            ->find();

        $table_group_field = "a.thickness,a.color,a.model,SUM(a.number) AS number_sum,SUM(a.number*a.one_area) AS one_area_sum,'' AS basic_price,'' AS ingots_price,'' AS ingots_price2,'' AS float_price,'' AS plate_price,'' AS color_price,SUM(a.bend) AS bend_price,'' AS note,group_concat(a.id) as archives_ids";
        $table_group_data = ArchivesModel::getList($order_id,$table_group_field,'a.thickness,a.color,a.model','a.thickness,a.color,a.model',$join,$where);
        $table_group_head = [['板厚','颜色','铝板版型','件数','面积(M²)','基价','浮动金额','板型加价','特殊颜色','开料刀数加价','铝板单价','金额(元)']];

        $table_extra = ArchivesModel::getList($order_id,'a.model_sn,a.number','','',$join,$where,'mill_order_archives_extra');

        $table_arr = self::fromArchivesTabale($order,$table_group_data,$table_group_head,$table_extra);

        $table_arr['order_info'] = array_merge($table_arr['order_info'],$order);

        return $table_arr;
    }
    // 表格制作
    //print 0:编辑模式 1:打印模式 2:导出模式
    public static function fromArchivesTabale($data = [],$table_group_data = [],$table_group_head = [],$table_extra = []){

        if(!empty($table_group_data)){

            $sum_group_number = 0;
            $sum_group_area = 0;
            $sum_group_price = 0;
            //input框设置
            $group_data_input = [
                'basic_price'           =>  [
                    'val'               =>  '',
                    'type'              =>  'number',
                    'update_price'      =>  true,
                ],
                'ingots_price'          =>  [
                    'val'               =>  '',
                    'type'              =>  'hidden',
                    'update_price'      =>  false,
                ],
                'ingots_price2'         =>  [
                    'val'               =>  '',
                    'type'              =>  'hidden',
                    'update_price'      =>  false,
                ],
                /*'ingots_time'           =>  [
                    'val'               =>  '',
                    'type'              =>  'text',
                    'update_price'      =>  false,
                ],*/
                'float_price'           =>  [
                    'val'               =>  '',
                    'update_price'      =>  true,
                    'type'              =>  'number',
                ],
                'plate_price'           =>  [
                    'val'               =>  '',
                    'type'              =>  'number',
                    'update_price'      =>  true,
                ],
                'color_price'           =>  [
                    'val'               =>  '',
                    'type'              =>  'number',
                    'update_price'      =>  true,
                ],
                'bend_price'            =>  [
                    'val'               =>  '',
                    'type'              =>  'number',
                    'update_price'      =>  true,
                ],
            ];

            $i = 1;
            foreach ($table_group_data as &$tgd){

                //设置唯一标识
                $data_group = 'group_'.md5($tgd['thickness'].'|||'.$tgd['color'].'|||'.$tgd['model']);

                $tgd_where = ['order_id'=>$data['id'],'color'=>$tgd['color'],'thickness'=>$tgd['thickness'],'model'=>$tgd['model']];

                $archives_price = Db::name('mill_order_archives_initial_price')->where($tgd_where)->find();
                $price = 0;
                $price_id = 0;
                $price_time = time();
                if(!empty($archives_price)){
                    $price_id = $archives_price['id'];
                    $price = $archives_price['price'];
                    $price_time = $archives_price['create_time'];
                    foreach ($group_data_input as $input_key=>$input_info){
                        $group_data_input[$input_key]['val'] = $archives_price[$input_key];
                    }
                }

                $hidden_input = '';
                foreach ($tgd as $tgd_key=>$tgd_val){
                    if(!empty($group_data_input[$tgd_key])){
                        //输入框类型
                        $input_type = !empty($group_data_input[$tgd_key]['type'])?$group_data_input[$tgd_key]['type']:'text';
                        //是否更新计算铝板单价
                        $is_update_price = '';
                        if(!empty($group_data_input[$tgd_key]['update_price']))$is_update_price = "{$data_group}_sum_price";
                        if(!empty($group_data_input[$tgd_key]['val']))$tgd_val = $group_data_input[$tgd_key]['val'];
                        //input框设置
                        if($input_type == 'hidden'){
                            $hidden_input .= '<input class="form-control group_input _'.$tgd_key.' '.$is_update_price.'" type="hidden" name="price_arr['.$i.']['.$tgd_key.']" value="'.$tgd_val.'">';
                            unset($tgd[$tgd_key]);
                        }
                        else $tgd[$tgd_key] = '[0]
                    <input class="form-control group_input _'.$tgd_key.' '.$is_update_price.'" type="'.$input_type.'" name="price_arr['.$i.']['.$tgd_key.']" value="'.$tgd_val.'" data-group="'.$data_group.'">';
                    }
                }

                //----------------------单价-------------------------
                $price_html = '[0]
                    <input type="hidden" name="price_arr['.$i.'][id]" value="'.$price_id.'">
                    <input type="hidden" name="price_arr['.$i.'][order_id]" value="'.$data['id'].'">
                    <input type="hidden" name="price_arr['.$i.'][create_time]" value="'.$price_time.'">
                    <input type="hidden" name="price_arr['.$i.'][color]" value="'.$tgd['color'].'">
                    <input type="hidden" name="price_arr['.$i.'][thickness]" value="'.$tgd['thickness'].'">
                    <input type="hidden" name="price_arr['.$i.'][model]" value="'.$tgd['model'].'">
                    <input type="hidden" name="price_arr['.$i.'][note]" value="'.$tgd['note'].'" class="_ingots_note">
                    '.$hidden_input.'
                    <input id="'.$data_group.'_price" class="form-control group_price" type="number" name="price_arr['.$i.'][price]" value="'.$price.'" data-one_area_sum="'.$tgd['one_area_sum'].'"  data-i="'.$i.'">
                ';
                $tgd['price'] = $price_html;
                $tgd['price_sum'] = '<span class="group_price_all" id="area_sum_'.$i.'">'.round($price*$tgd['one_area_sum'],2).'</span>';

                unset($tgd['note']);
                unset($tgd['archives_ids']);
                $sum_group_number += $tgd['number_sum'];
                $sum_group_area += $tgd['one_area_sum'];
                $sum_group_price += round($price*$tgd['one_area_sum'],2);
                //板厚统计
                if(!isset($table_group_data_type_sarr[$data['id']]['thickness'][$tgd['thickness']]))$table_group_data_type_sarr[$data['id']]['thickness'][$tgd['thickness']] = 0;
                $table_group_data_type_sarr[$data['id']]['thickness'][$tgd['thickness']] += $tgd['one_area_sum'];

                $i++;
            }

            //-----------------------------其他合计计价---------------------------------
            //类型 0:面积价 1:铝锭价 2:开槽 3: 焊缝 4:矩管
            $tgd_type_arr = [
                //合计开槽
                ['field'=>'slot','title'=>'合计开槽(M)','type'=>2,'sum_eq'=>4],
                //合计焊缝
                ['field'=>'weld','title'=>'合计焊缝(M)','type'=>3,'sum_eq'=>4],
                //矩管长度
                //['field'=>'torque','title'=>'开孔个数','type'=>4,'sum_eq'=>4],
            ];
            if(count($tgd_type_arr)>0){
                foreach ($tgd_type_arr as $ttav){

                    $i++;
                    $ld_field = $ttav['field'];
                    $ld_title = $ttav['title'];
                    $ld_sum_eq = $ttav['sum_eq'];
                    $ld_type = $ttav['type'];//类型 0:面积价 1:焊缝 2: 刨槽 3:开孔

                    $price_arr_where = ['order_id'=>$data['id'],'type'=>$ld_type];
                    $tgpv = Db::name('mill_order_archives_initial_price')->where($price_arr_where)->find();

                    $ld_id = !empty($tgpv['id'])?$tgpv['id']:'';
                    $ld_order_id = !empty($tgpv['order_id'])?$tgpv['order_id']:$data['id'];
                    $ld_time = !empty($tgpv['create_time'])?$tgpv['create_time']:time();
                    $ld_pirce = !empty($tgpv['price'])?$tgpv['price']:0;
                    $ld_row_area = $data[$ld_field];

                    $ld_price_sum = round($ld_row_area*$ld_pirce,2);//四舍五入，保留2位

                    $ld_field_html = '<div class="'.$ld_field.'_sum">'.$ld_row_area.'</div>';
                    $ld_input_html = '[0]
                    
                <input type="hidden" name="price_arr['.$i.'][id]" value="'.$ld_id.'">
                <input type="hidden" name="price_arr['.$i.'][order_id]" value="'.$ld_order_id.'">
                <input type="hidden" name="price_arr['.$i.'][create_time]" value="'.$ld_time.'">
                <input type="hidden" name="price_arr['.$i.'][type]" value="'.$ld_type.'">
                <input type="hidden" name="price_arr['.$i.'][row_area]" value="'.$ld_row_area.'" class="'.$ld_field.'_row_area">
                
                <input class="form-control '.$ld_field.'_val group_price" type="number" name="price_arr['.$i.'][price]" value="'.$ld_pirce.'" data-one_area_sum="'.$ld_row_area.'"  data-i="'.$i.'">
                
                ';
                    $ld_price_html = '<span class="group_price_all" id="area_sum_'.$i.'">'.$ld_price_sum.'</span>';

                    $new_ttav = ['','',$ld_title,'','','','','','','',$ld_input_html,$ld_price_html];
                    $new_ttav[$ld_sum_eq] = $ld_field_html;

                    $table_group_data[] = $new_ttav;

                    $sum_group_price += $ld_price_sum;
                }
            }

            //-------------------------------配件计价-----------------------------------
            if(!empty($table_extra)){
                foreach ($table_extra as $te){
                    $i++;
                    $ld_type = 0;//类型 0:面积价
                    $ld_field = 'model_sn';
                    $ld_sum_eq = 3;

                    $price_arr_where = ['order_id'=>$data['id'],'model_sn'=>$te['model_sn']];
                    $tgpv = Db::name('mill_order_archives_initial_price')->where($price_arr_where)->find();

                    $ld_id = !empty($tgpv['id'])?$tgpv['id']:'';
                    $ld_order_id = !empty($tgpv['order_id'])?$tgpv['order_id']:$data['id'];
                    $ld_time = !empty($tgpv['create_time'])?$tgpv['create_time']:time();
                    $ld_pirce = !empty($tgpv['price'])?$tgpv['price']:0;
                    $ld_model_sn = $te['model_sn'];
                    $ld_row_area = $te['number'];

                    $ld_price_sum = round($ld_row_area*$ld_pirce,2);//四舍五入，保留2位

                    $ld_field_html = '<div class="'.$ld_field.'_sum">'.$ld_row_area.'</div>';
                    $ld_input_html = '[0]
                    
                <input type="hidden" name="price_arr['.$i.'][id]" value="'.$ld_id.'">
                <input type="hidden" name="price_arr['.$i.'][order_id]" value="'.$ld_order_id.'">
                <input type="hidden" name="price_arr['.$i.'][create_time]" value="'.$ld_time.'">
                <input type="hidden" name="price_arr['.$i.'][type]" value="'.$ld_type.'">
                <input type="hidden" name="price_arr['.$i.'][model_sn]" value="'.$ld_model_sn.'">
                <input type="hidden" name="price_arr['.$i.'][number]" value="'.$ld_row_area.'" class="'.$ld_field.'_row_area">
                
                <input class="form-control '.$ld_field.'_val group_price" type="number" name="price_arr['.$i.'][price]" value="'.$ld_pirce.'" data-one_area_sum="'.$ld_row_area.'"  data-i="'.$i.'">
                
                ';
                    $ld_price_html = '<span class="group_price_all" id="area_sum_'.$i.'">'.$ld_price_sum.'</span>';

                    $new_ttav = ['','',$te['model_sn'],'','','','','','','',$ld_input_html,$ld_price_html];
                    $new_ttav[$ld_sum_eq] = $ld_field_html;

                    $table_group_data[] = $new_ttav;

                    $sum_group_number += $te['number'];
                    $sum_group_price += $ld_price_sum;
                }
            }

            //-------------------------------铝锭计价-----------------------------------
            $table_group_price_arr = Db::name('mill_order_archives_initial_price')->where(['order_id'=>$data['id'],'type'=>1])->select();

            //根据板厚数量生成
            $tgp_thickness_arr = $table_group_data_type_sarr[$data['id']]['thickness'];
            //$tgp_count = count($table_group_price_arr)>0?count($table_group_price_arr):(count($tgp_thickness_arr)+1);
            $tgp_count = (count($tgp_thickness_arr)+1);
            for($pi=0;$pi<$tgp_count;$pi++){
                $tgpv = !empty($table_group_price_arr[$pi])?$table_group_price_arr[$pi]:'';

                $_thickness = key($tgp_thickness_arr);

                $ld_title_0 = !empty($table_group_price_arr[0])?$table_group_price_arr[0]['title']:'';
                $ld_title_class = 'group_lvdingjia';
                if(empty($_thickness)){
                    $ld_title_0 = '';
                    $ld_title_class = '';
                }

                $i++;
                $ld_id = !empty($tgpv['id'])?$tgpv['id']:'';
                $ld_order_id = !empty($tgpv['order_id'])?$tgpv['order_id']:$data['id'];
                $ld_time = !empty($tgpv['create_time'])?$tgpv['create_time']:time();
                $ld_title = !empty($tgpv['title'])?$tgpv['title']:$ld_title_0;
                $ld_thickness = !empty($tgpv['thickness'])?$tgpv['thickness']:$_thickness;
                $ld_pirce = !empty($tgpv['price'])?$tgpv['price']:0;
                $ld_area = !empty($tgpv['row_area'])?$tgpv['row_area']:(isset($tgp_thickness_arr[$_thickness])?$tgp_thickness_arr[$_thickness]:'');
                $ld_type = 1;//类型 0:面积价 1:铝锭价 2:其他价
                $ld_price_sum = round($ld_pirce*floatval($ld_area));//四舍五入，取整

                $ld_thickness_html = '[0]
                <input class="form-control" type="hidden" placeholder="请填写板厚" name="price_arr['.$i.'][thickness]" value="'.$ld_thickness.'" data-i="'.$i.'">'.$ld_thickness;

                $ld_input_html = '[0]
                <input class="form-control area" type="number" name="price_arr['.$i.'][row_area]" value="'.$ld_area.'" data-area-type="group_row_area_'.$i.'" data-toAreaSum="no" data-i="'.$i.'">';

                $ld_field_html = '[3:1]
                <input type="hidden" name="price_arr['.$i.'][id]" value="'.$ld_id.'">
                <input type="hidden" name="price_arr['.$i.'][order_id]" value="'.$ld_order_id.'">
                <input type="hidden" name="price_arr['.$i.'][create_time]" value="'.$ld_time.'">
                <input type="hidden" name="price_arr['.$i.'][type]" value="'.$ld_type.'">
                    
                <input class="form-control '.$ld_title_class.'" type="text" placeholder="请填写铝锭价标题" name="price_arr['.$i.'][title]" value="'.$ld_title.'" data-i="'.$i.'">';
                $ld_area_html = '[0]
                <input class="form-control group_price group_row_area_'.$i.'_val" type="number" name="price_arr['.$i.'][price]" value="'.$ld_pirce.'" data-one_area_sum="'.$ld_area.'" data-i="'.$i.'">
                
                ';
                $ld_price_html = '<span class="group_price_all" id="area_sum_'.$i.'">'.$ld_price_sum.'</span>';


                $table_group_data[] = [$ld_thickness_html,$ld_field_html,$ld_input_html,'','','','','',$ld_area_html,$ld_price_html];

                $sum_group_price += $ld_price_sum;

                unset($tgp_thickness_arr[$_thickness]);
            }

            $table_group_data[] = ["[12:1]
                <div style='text-align: right'>合计数量：<a style='font-size: 25px;'>".$sum_group_number."</a>  合计面积(M²)：<a style='font-size: 25px;'>".$sum_group_area."</a>  焊缝长度：<a id='sum_group_weld' style='font-size: 25px;'>".$data['weld']."</a>  刨槽长度：<a id='sum_group_slot' style='font-size: 25px;'>".$data['slot']."</a>  开孔个数：<a id='sum_group_torque' style='font-size: 25px;'>".$data['torque']."</a> 合计金额(元)：<a id='sum_group_price' style='font-size: 25px;'>".$sum_group_price."</a><input type='hidden' name='sum_group_price' value='{$sum_group_price}'></div>"];

        }

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                  
                  $("#table-list_archives_group").find("th").eq(4).css("width","130px");
                  $("#table-list_archives_group").find("th").eq(8).css("width","130px");
                  $("#table-list_archives_group").find("th").eq(0).css("width","50px");
                  $("#table-list_archives_group").find("th").eq(1).css("width","180px");
                  $("#table-list_archives_group").find("th").eq(2).css("width","150px");
                  //监听铝锭价设置
                  $("#_ingots_price").bind("input propertychange", function() {
                      var _ingots_price = $(this).val();
                      var _ingots_price2 = $("#_ingots_price2").val();
                      $("._ingots_price").val(_ingots_price);
                      //同步更新差价
                      $("#_ingots_price_sum").val((_ingots_price-_ingots_price2));
                      //同步更新铝锭价标题
                      var title = "合同铝锭价"+_ingots_price+"元/吨，下单铝锭价"+_ingots_price2+"元/吨";
                      $(".group_lvdingjia").val(title);
                      //$("._ingots_price").each(function(i) {
                      //  updateSumPrice($("._ingots_price").eq(i));
                      //});
                  });
                  //监听下单铝锭价设置
                  $("#_ingots_price2").bind("input propertychange", function() {
                      var _ingots_price = $("#_ingots_price").val();
                      var _ingots_price2 = $(this).val();
                      $("._ingots_price2").val(_ingots_price2);
                      //同步更新差价
                      $("#_ingots_price_sum").val((_ingots_price-_ingots_price2));
                      //同步更新铝锭价标题
                      var title = "合同铝锭价"+_ingots_price+"元/吨，下单铝锭价"+_ingots_price2+"元/吨";
                      $(".group_lvdingjia").val(title);
                      //$("._ingots_price").each(function(i) {
                      //  updateSumPrice($("._ingots_price").eq(i));
                      //});
                  });
                  //监听铝锭价日期设置
                  $("#_ingots_time").bind("input propertychange", function() {
                      $("._ingots_time").val($(this).val());
                  });
                  //监听备注设置
                  $("#_ingots_note").bind("input propertychange", function() {
                      console.log(1);
                      $("._ingots_note").val($(this).val());
                  });
                  //监听加价设置
                  $(".group_input").bind("input propertychange", function() {
                      updateSumPrice($(this));
                  });
                  //监听单价设置
                  $(".group_price").bind("input propertychange", function() {
                      updatePrice($(this));
                  });
                  //监听开槽等面积设置
                  $(".area").bind("input propertychange", function() {
                      var obj = $(this);
                      var area = obj.val();
                      var type = obj.data("area-type");
                      var group = obj.data("group");
                      var toAreaSum = obj.data("toAreaSum");
                      var sum_area = 0;
                      
                      if(toAreaSum == "no"){
                          //不更新合计面积
                          sum_area = obj.val();
                      }
                      else {
                          var sum_group_area = 0;
                          //更新合计面积
                          $(".area[data-area-type="+type+"]").each(function() {
                            var each_group = $(this).data("group");
                            var val = parseFloat($(this).val());
                            if(isNaN(val)){
                                val = 0;
                            }
                            sum_area += val;
                            if(group == each_group){
                                sum_group_area += val;
                            }
                          });
                          //四舍五入保留六位小数
                          sum_area = Math.round(sum_area*1000000)/1000000;
                          sum_group_area = Math.round(sum_group_area*1000000)/1000000;
                          $("#"+group+" div").text(sum_group_area);
                          $("#"+group+" input").val(sum_group_area);
                          $("."+type+"_sum").text(sum_area);
                          $("#sum_group_"+type).text(sum_area);
                      }
                      
                      //更新合计价格
                      $("."+type+"_row_area").val(sum_area);
                      $("."+type+"_val").data("one_area_sum",sum_area);
                      updatePrice($("."+type+"_val"));
                      
                  });
                  //更新铝板单价
                  function updateSumPrice(obj) {
                      
                      var group = obj.data("group");
                      
                      var sum_price = 0;
                      $("."+group+"_sum_price").each(function() {
                          var price = $(this).val();
                          if(!price)price = 0;
                          sum_price += parseFloat(price);
                      });
                      //console.log(sum_price);
                      //四舍五入，保留2位
                      sum_price = Math.round(sum_price*100)/100;
                      $("#"+group+"_price").val(sum_price);
                      //更新金额
                      updatePrice($("#"+group+"_price"));
                  }
                  //更新合计价格
                  function updatePrice(obj) {
                      var price = obj.val();
                      var price_sum = obj.data("one_area_sum")*price;
                      //四舍五入，保留2位
                      price_sum = Math.round(price_sum*100)/100;
                      var i = obj.data("i");
                      $("#area_sum_"+i).text(price_sum);
                      
                      var sum_group_price = 0;
                      $(".group_price_all").each(function() {
                        sum_group_price += parseFloat($(this).text());
                      });
                      //四舍五入，保留2位
                      sum_group_price = Math.round(sum_group_price*100)/100;
                      $("#sum_group_price").text(sum_group_price);
                      $("input[name=\'sum_group_price\']").val(sum_group_price);
                  }
                })
            </script>';

        return ['head'=>$table_group_head,'data'=>$table_group_data,'js'=>$js,'order_info'=>['sum_group_price'=>$sum_group_price]];
    }

    // 打印模板
    //print 1:打印模式 2:导出模式
    public static function toHtml($data = [],$table = [],$print = 1){

        //缩放比例
        $table_scaling = 1;

        //$html = '<html><style>th{font-size: 18px;font-weight: bold;}td{}</style><body style="margin: 4px;">';
        $html = '<html><style>th{font-size: 12px;font-weight: bold;}td{font-size: 12px;}</style><body style="margin: 4px;">';

        //头部
        $html .= '<table border="1" style="text-align: center;border-collapse: collapse;width: '.(21/$table_scaling).'cm;transform-origin: 0 0;"><thead>
                        <tr><th colspan="12" style="font-size: 25px;font-weight: bold;"><img style="width: 50px;margin-bottom: -20px;" class="td-none" src="'.config('template.tpl_replace_string')['__ADMIN_IMG__'].'/logo2.jpg">'.config('web_site_title').'</th></tr>
                    ';
        $table_arr = self::fromTabale($data,$table,1);
        foreach ($table_arr as $tk=>$tv){
            //头
            if($tk == 'head'){
                foreach ($tv as $tvv){

                    $html .= '<tr>';
                    foreach ($tvv as $tvvv){

                        $v = OrderModel::tableParseCell($tvvv);

                        $html .= '
                            <th rowspan="'.$v['rowspan'].'" colspan="'.$v['colspan'].'">'.$v['value'].'</th>
                            ';
                    }
                    $html .= '</tr>';
                }
                $html .= '</thead>';
            }
            //体
            elseif($tk == 'data'){
                $html .= '<tbody>';
                foreach ($tv as $tvv){

                    $html .= '<tr>';
                    foreach ($tvv as $tvvv){

                        $v = OrderModel::tableParseCell($tvvv);

                        $v['value'] = str_replace("\n","<br>",$v['value']);
                        $html .= '
                            <td rowspan="'.$v['rowspan'].'" colspan="'.$v['colspan'].'">'.$v['value'].'</td>
                            ';
                    }
                    $html .= '</tr>';
                }
                $html .= '</tbody>';
            }
        }
        $html .= '</table>';

        $js = 'window.print();';
        if($print == 2){
            $js = '$("table").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: "",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "发货单",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });';
        }
        //js
        $html .= '
                    <script src="'.config('template.tpl_replace_string')['__ADMIN_JS__'].'/core/jquery.min.js?v=20180327"></script>
                    <script src="'.config('template.tpl_replace_string')['__STATIC__'].'/common/js/jquery.table2excel.js?v='.date('Ymd').'"></script>
                    <script type="text/javascript">
                        //去除边框
                        $(".td-none").parent().css("border-style","hidden")
                        //设置头部边框
                        $(".td-top").parent().css("border-top","black");
                        //设置底部边框
                        $(".td-bottom").parent().css("border-bottom","black");
                        //设置高度
                        $(".td-50").parent().css("height","50px");
                        //设置向下对齐
                        $(".text-bottom").parent().css("vertical-align","bottom");
                        //设置文字上下间距
                        $(".text-height").parent().css("line-height","28px");
                        //设置文字缩放比例
                        $("th,td").css("-webkit-transform","scale('.$table_scaling.')");
                        //设置文字缩放后左对齐
                        $(".scale-left").parent().css("transform-origin","0");
                        
                        '.$js.'
                    </script>';

        return $html;
    }

    //根据发货单生成对账单
    public static function audit($address_id = 0){

        return '';
        //发货单信息
        $address = Db::name('mill_order_archives_address')->where(['id'=>$address_id])->find();
        //发货时间
        $address_time = strtotime($address['address_date']);
        //最后一次发货时间
        $address_last_time = Db::name('mill_order_archives_give')->where(['order_pid'=>$address['order_pid']])->order('address_time desc')->value('address_time');
        //订单信息
        $order = Db::name('mill_order')->where(['id'=>$address['order_pid']])->find();
        $order['company'] = Db::name('mill_client')->where(['id'=>$order['client_id']])->value('company');
        //判断发货的工程批次是否已全部计价
        $order_ids = Db::name('mill_order_archives_give')->where(['address_sn'=>$address['address_sn']])->column('DISTINCT order_id');
        $initial_price_status = Db::name('mill_order')->where([['id','in',implode(',',$order_ids)],['initial_price_status','<',2]])->count();
        if(!empty($initial_price_status))return '';
        //获取发货状态，是否已完全发完
        $give_address_where = [
            ['order_pid','=',$order['order_pid']],
            ['quality_status','>',-2],
            ['status','<',4],
        ];
        $give_address = Db::name('mill_order_archives_give')->where($give_address_where)->value('id');

        //获取收款信息
        $finance_config = Db::name('mill_order_contract')->where(['order_id'=>$address['order_pid']])->find();
        $finance_type = $finance_config['finance_type'];//收款方式
        $finance_money = $finance_config['finance_money'];//定金
        $late_money = $finance_config['late_money'];//滞纳金
        $late_time = strtotime($finance_config['late_time']);//滞纳金归还时间
        $finance_config = json_decode($finance_config['finance_config'],true);//收款配置
        $finance_config = !empty($finance_config[$finance_type])?$finance_config[$finance_type]:'';
        //实收金额
        $sum_money = 0;
        //应收金额
        $rece_money = 0;
        //预付金额
        $advance_money = 0;
        //质保金额
        $quality_money = 0;
        //累计到下次结算的金额
        $next_money = 0;
        //预计收款日期
        $rece_time = time();
        //获取累积方量
        $row_area = Db::name('mill_order_archives_give')->alias('g')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where([['address_sn','in',$address['address_sn']]])->sum('a.one_area');
        $row_area = floatval($row_area);

        $add = [
            'create_time'           =>  time(),
            'update_time'           =>  time(),
            'address_time'          =>  $address_time,
            'address_sns'           =>  $address['address_sn'],
            'order_pid'             =>  $order['order_pid'],
            'order_sn'              =>  $order['order_sn'],
            'handle'                =>  $order['archives_handle'],
            'row_area'              =>  $row_area,
            //收款
            'money'                 =>  0,
            'rece_money'            =>  0,
            'rece_time'             =>  time(),
        ];
        //根据收款方式类型计算对账金额
        $audit_id = 0;
        switch ($finance_type){
            //先款后货
            case 0:
                //新增对账单
                $audit_id = Db::name('mill_audit')->insertGetId($add);
                //获取对账单信息
                $audit = AuditModel::fromData($audit_id);
                //实收金额
                $sum_money = floatval($audit['sum_money']);
                //应收金额
                $rece_money = floatval($audit['sum_money']);
                break;
            //按发货时间对账，并结算
            //发货后，第_2_个月_20_日对账，第_3_个月_30_日前支付_80_%，余下_20_%累计到下一批发货单结算
            case 1:
                //查询当月对账单
                $start_time = strtotime(date('Y-m'));
                $end_time = strtotime('+1 month',$start_time)-1;
                //更新对账日期
                $month = $finance_config['recon_month']-1;
                $day = $finance_config['recon_day'];
                $add['rece_time'] = strtotime(date("Y-m-{$day}",strtotime("+{$month} month",$start_time)));

                $audit_where = [
                    ['order_pid','=',$order['order_pid']],
                    ['create_time','between',"{$start_time},{$end_time}"],
                ];
                $audit = Db::name('mill_audit')->where($audit_where)->find();
                //新增对账单
                if(empty($audit))$audit_id = Db::name('mill_audit')->insertGetId($add);
                //更新对账单
                else{
                    $audit_id = $audit['id'];
                    //更新发货单
                    $address_sns = explode(',',$audit['address_sns']);
                    $address_sns[] = $address['address_sn'];
                    $address_sns = implode(',',array_unique($address_sns));
                    Db::name('mill_audit')->where(['id'=>$audit_id])->update(['address_sns'=>$address_sns]);
                }
                //获取对账单信息
                $audit = AuditModel::fromData($audit_id);

                //获取上次剩余未结算的金额
                $prev_money = Db::name('mill_audit')->where([['id','<',$audit_id]])->order('id desc')->value('next_money');
                //应收金额
                $rece_money = floatval($audit['sum_money'])+floatval($prev_money);
                //实收金额
                $sum_money = $rece_money;
                //发货还有剩余
                if(!empty($give_address))$sum_money = round($rece_money*($finance_config['pay_money_scale']/100),2);
                //累计到下次结算的金额
                $next_money = $rece_money-$sum_money;
                //更新对账单，剩余未结算的金额
                //Db::name('mill_audit')->where(['id'=>$audit_id])->update(['next_money'=>$next_money]);
                //更新预计收款日期
                $month = $finance_config['pay_month']-1;
                $day = $finance_config['pay_day'];
                $rece_time = strtotime(date("Y-m-{$day}",strtotime("+{$month} month",$start_time)));
                break;
            //发货进度款
            //累计达到进度款_60_万元
            //不管_2_个月内是否达标，也要在_10_天内对账
            //收到发票后，_5_天内支付总货款的_80_%，剩余_20_%不记入下次进度款
            //设置最终收款时间
            case 2:
                //更新对账日期
                $month = $finance_config['recon_month'];
                $add['rece_time'] = strtotime("+{$month} month",strtotime(date('Y-m-d')));
                $rece_time = $add['rece_time'];

                //查询最新的最账单
                $audit_where = [
                    ['order_pid','=',$order['order_pid']],
                ];
                $audit = Db::name('mill_audit')->where($audit_where)->order('id desc')->find();
                //如果超过对账日期，则生成新的对账单
                if($add['rece_time'] <= time())$audit = '';
                //如果超过累积进度款，也生成新的对账单
                elseif($audit['money'] >= $finance_config['recon_money']){
                    $audit = '';
                    //更新对账时间
                    $rece_time = strtotime(date('Y-m-d'));
                    Db::name('mill_audit')->where(['id'=>$audit['id']])->update(['rece_time'=>$rece_time]);
                }
                //新增对账单
                if(empty($audit))$audit_id = Db::name('mill_audit')->insertGetId($add);
                //更新对账单
                else{
                    $audit_id = $audit['id'];
                    //更新发货单
                    $address_sns = explode(',',$audit['address_sns']);
                    $address_sns[] = $address['address_sn'];
                    $address_sns = implode(',',array_unique($address_sns));
                    Db::name('mill_audit')->where(['id'=>$audit_id])->update(['address_sns'=>$address_sns]);
                }
                //获取对账单信息
                $audit = AuditModel::fromData($audit_id);

                //获取上次剩余未结算的金额
                $prev_money = Db::name('mill_audit')->where([['id','<',$audit_id]])->order('id desc')->value('next_money');
                //应收金额
                $rece_money = floatval($audit['sum_money']);
                //实收金额
                $sum_money = $rece_money + floatval($prev_money);
                //累计到下次结算的金额
                $next_money = 0;
                //发货还有剩余
                if(!empty($give_address)){
                    //实收金额
                    $sum_money = round($rece_money*($finance_config['pay_money_scale']/100),2);
                    //累计到下次结算的金额
                    $next_money = floatval($prev_money)+($rece_money-$sum_money);
                }
                //更新对账单，剩余未结算的金额
                //Db::name('mill_audit')->where(['id'=>$audit_id])->update(['next_money'=>$next_money]);
                //更新预计收款日期
                //对账日期，(_10_天内对账)+(收到发票后，_5_天内支付)
                $day_num = $finance_config['recon_day_num']+$finance_config['pay_day_num'];
                $rece_time += ($day_num*86400);
                break;
            //月结
            //设置月结_75_%
            //当月货款，第_2_个月前对账，第_2_个月_10_前支付_75_%
            //全部发完货后，结算剩余_97_%，_180_天后结算剩余_3_%
            case 3:
                //查询当月对账单
                $start_time = strtotime(date('Y-m'));
                $end_time = strtotime('+1 month',$start_time)-1;
                //更新对账日期
                $month = $finance_config['recon_month']-1;
                $add['rece_time'] = strtotime("+{$month} month",$start_time);

                $audit_where = [
                    ['order_pid','=',$order['order_pid']],
                    ['create_time','between',"{$start_time},{$end_time}"],
                ];
                $audit = Db::name('mill_audit')->where($audit_where)->find();
                //新增对账单
                if(empty($audit))$audit_id = Db::name('mill_audit')->insertGetId($add);
                //更新对账单
                else{
                    $audit_id = $audit['id'];
                    //更新发货单
                    $address_sns = explode(',',$audit['address_sns']);
                    $address_sns[] = $address['address_sn'];
                    $address_sns = implode(',',array_unique($address_sns));
                    Db::name('mill_audit')->where(['id'=>$audit_id])->update(['address_sns'=>$address_sns]);
                }
                //获取对账单信息
                $audit = AuditModel::fromData($audit_id);

                //获取上次剩余未结算的金额
                $prev_money = Db::name('mill_audit')->where([['id','<',$audit_id]])->order('id desc')->value('next_money');

                //发货还有剩余
                if(!empty($give_address)){
                    //应收金额
                    $rece_money = floatval($audit['sum_money']);
                    //实收金额
                    $sum_money = round($rece_money*($finance_config['pay_money_scale']/100),2);
                    //累计到下次结算的金额
                    $next_money = floatval($prev_money)+($rece_money-$sum_money);
                }
                //全部发完货
                else{
                    //应收金额
                    $rece_money = floatval($audit['sum_money'])+floatval($prev_money);
                    //实收金额
                    $sum_money = round($rece_money*($finance_config['pay_end_pay_scale']/100),2);
                    //累计到下次结算的金额
                    $next_money = $rece_money-$sum_money;
                    //生成最后一笔调账单
                    $end_finance = [
                        'create_time'           =>  time(),
                        'update_time'           =>  time(),
                        'address_time'          =>  $address_time,
                        'order_pid'             =>  $order['order_pid'],
                        'order_sn'              =>  $order['order_sn'],
                        'handle'                =>  $order['archives_handle'],
                        'audit_id'              =>  $audit_id,
                        //收款
                        'money'                 =>  $next_money,
                        'rece_money'            =>  $next_money,
                        'rece_time'             =>  $rece_time+($finance_config['pay_end_pay_num']*86400),
                    ];
                    //累计到下次结算的金额
                    $next_money = 0;
                }
                //更新预计收款日期
                $month = $finance_config['pay_month']-1;
                $day = $finance_config['pay_day'];
                $rece_time = strtotime(date("Y-m-{$day}",strtotime("+{$month} month",$start_time)));
                break;
            //货到付款
            //货到工地7日内付款
            //货到后__pay_day_num__日内付款，规定日期__pay_end_date_y__年__pay_end_date_m__月__pay_end_date_d__日后开始
            case 4:

                //规定日期，达到期限后开始收款
                $end_date = strtotime("{$finance_config['pay_end_date_y']}-{$finance_config['pay_end_date_m']}-{$finance_config['pay_end_date_d']}");
                //更新预计收款日期
                //未达到规定日期，默认收款日期未规定日期，并进行累加
                if(time()<$end_date){
                    $rece_time = $end_date;

                    //获取规定日期前，累积的对账单信息
                    $audit_where = [
                        ['order_pid','=',$order['order_pid']],
                        ['create_time','<=',$end_date],
                    ];
                    $audit = Db::name('mill_audit')->where($audit_where)->find();

                    if(empty($audit))$audit_id = Db::name('mill_audit')->insertGetId($add);
                    else{
                        //更新对账单
                        $audit_id = $audit['id'];
                        //更新发货单
                        $address_sns = explode(',',$audit['address_sns']);
                        $address_sns[] = $address['address_sn'];
                        $address_sns = implode(',',array_unique($address_sns));
                        Db::name('mill_audit')->where(['id'=>$audit_id])->update(['address_sns'=>$address_sns]);
                    }
                }
                //已达到规定日期，则从到货后，7天内付款
                else {
                    //$rece_time = strtotime(date("Y-m-d"))+($finance_config['pay_day_num']*86400);
                    $rece_time = strtotime(date("Y-m-d"));

                    $audit_id = Db::name('mill_audit')->insertGetId($add);
                }

                //获取对账单信息
                $audit = AuditModel::fromData($audit_id);
                //实收金额
                $sum_money = floatval($audit['sum_money']);
                //应收金额
                $rece_money = floatval($audit['sum_money']);

                break;
            //项目供货完毕后付款
            //项目供货完毕（距最后一车发货之日起20天内无新订单则视为供货完毕）的30天内付清该项目全部货款
            //项目供货完毕（距最后一车发货之日起20天内无新订单则视为供货完毕）的__pay_day_num__天内付清该项目全部货款
            case 5:
                //对账时间，发货后的第20天
                $rece_time += (20*86400);

                //查询最新的账单
                $audit_where = [
                    ['order_pid','=',$order['order_pid']],
                ];
                $audit = Db::name('mill_audit')->where($audit_where)->order('id desc')->find();
                //新增对账单
                if(empty($audit))$audit_id = Db::name('mill_audit')->insertGetId($add);
                //更新对账单
                else{
                    $audit_id = $audit['id'];
                    //更新发货单
                    $address_sns = explode(',',$audit['address_sns']);
                    $address_sns[] = $address['address_sn'];
                    $address_sns = implode(',',array_unique($address_sns));
                    Db::name('mill_audit')->where(['id'=>$audit_id])->update(['address_sns'=>$address_sns]);
                }
                //更新对账时间
                Db::name('mill_audit')->where(['id'=>$audit_id])->update(['rece_time'=>$rece_time]);

                //获取对账单信息
                $audit = AuditModel::fromData($audit_id);
                //实收金额
                $sum_money = floatval($audit['sum_money']);
                //应收金额
                $rece_money = floatval($audit['sum_money']);
                break;
            //押一付一
            //采用押一车货款的支付方式，即乙方发第一车货到甲方工地后，暂不付款，乙方在送第二车货之前，甲方支付乙方第一车货的全额货款
            //最后一车货采取先款后货的付款当时
            case 6:
                //更新对账日期
                $add['rece_time'] = 0;
                $rece_time = $add['rece_time'];

                //查询最新的账单
                $audit_where = [
                    ['order_pid','=',$order['order_pid']],
                ];
                $audit = Db::name('mill_audit')->where($audit_where)->order('id desc')->find();
                //对账时间，设置为0，等下一批发货再更新
                if(!empty($audit))$rece_time = time();

                //更新上一批账单的对账时间
                if(!empty($audit)){
                    //更新对账单
                    Db::name('mill_audit')->where(['id'=>$audit['id']])->update(['rece_time'=>$rece_time]);
                    //更新子调账单
                    Db::name('mill_finance')->where(['audit_id'=>$audit['id']])->update(['rece_time'=>$rece_time]);
                }

                //新增对账单
                $audit_id = Db::name('mill_audit')->insertGetId($add);
                //获取对账单信息
                $audit = AuditModel::fromData($audit_id);
                //实收金额
                $sum_money = floatval($audit['sum_money']);
                //应收金额
                $rece_money = floatval($audit['sum_money']);

                break;
            //按方量付款
            //供货达2000㎡为一付款节点，到达付款节点后7天内完成供货部分货款核对，并支付2000㎡的全额货款，以此类推
            case 7:

                //更新对账日期
                $rece_time = 0;
                //如果已发货完，或者当前发货单方量已达标，则更新对账日期
                if(empty($give_address) || $add['row_area'] >= $finance_config['pay_area_num'])$rece_time = time();
                //累积方量
                $row_area = 0;

                //查询最新的对账单
                $audit_where = [
                    ['order_pid','=',$order['order_pid']],
                ];

                $audit = Db::name('mill_audit')->where($audit_where)->order('id desc')->find();
                if(!empty($audit)){
                    //获取累积方量
                    $row_area = Db::name('mill_order_archives_give')
                        ->alias('g')
                        ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                        ->where([['address_sn','in',$audit['address_sns']]])
                        ->sum('a.one_area');
                    $row_area = floatval($row_area);
                }
                //如果上一批方量已达标，则生成新的对账单
                if(empty($audit) || $row_area >= $finance_config['pay_area_num']){
                    $audit_id = Db::name('mill_audit')->insertGetId($add);
                    $audit = Db::name('mill_audit')->where(['id'=>$audit_id])->find();
                }
                //如果上一批方量未达标，则更新对账单
                $audit_id = $audit['id'];
                //更新发货单
                $address_sns = explode(',',$audit['address_sns']);
                $address_sns[] = $address['address_sn'];
                $address_sns = implode(',',array_unique($address_sns));

                //获取累积方量
                $row_area = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where([['address_sn','in',$address_sns]])
                    ->sum('a.one_area');
                $row_area = floatval($row_area);
                //如果方量已达标，则更新对账时间
                if($row_area >= $finance_config['pay_area_num'])$rece_time = strtotime(date('Y-m-d'));

                //更新对账单
                Db::name('mill_audit')->where(['id'=>$audit_id])->update(['address_sns'=>$address_sns,'rece_time'=>$rece_time,'row_area'=>$row_area]);

                //获取对账单信息
                $audit = AuditModel::fromData($audit_id);
                //实收金额
                $sum_money = floatval($audit['sum_money']);
                //应收金额
                $rece_money = floatval($audit['sum_money']);
                break;
            //方量月结或进度款
            //3000㎡结算一次或每月底结算上月供货款
            //收到发票后，支付批次结算货款额的_80_%，剩余_20_%不记入下次进度款
            case 8:
                //更新对账日期
                $month = $finance_config['recon_month'];
                $recon_day = $finance_config['recon_day_num'];
                $add['rece_time'] = strtotime("+{$month} month",strtotime(date('Y-m')))+($recon_day*86400);
                //如果已发货完，或者当前发货单方量已达标，则更新对账日期
                if(empty($give_address) || $add['row_area'] >= $finance_config['pay_area_num'])$add['rece_time'] = time();
                $rece_time = $add['rece_time'];

                //查询最新的对账单
                $audit_where = [
                    ['order_pid','=',$order['order_pid']],
                ];
                $audit = Db::name('mill_audit')->where($audit_where)->order('id desc')->find();
                if(!empty($audit)){
                    //获取累积方量
                    $audit['row_area'] = Db::name('mill_order_archives_give')
                        ->alias('g')
                        ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                        ->where([['address_sn','in',$audit['address_sns']]])
                        ->sum('a.one_area');
                    $audit['row_area'] = floatval($audit['row_area']);
                }
                //如果超过对账日期，则生成新的对账单
                if(empty($audit) || $audit['rece_time'] <= time())$audit = '';
                //如果上一批对账单未超过累积方量，则累加
                elseif($audit['row_area'] < $finance_config['pay_area_num']){
                    //更新发货单
                    $address_sns = explode(',',$audit['address_sns']);
                    $address_sns[] = $address['address_sn'];
                    $address_sns = implode(',',array_unique($address_sns));
                    Db::name('mill_audit')->where(['id'=>$audit_id])->update(['address_sns'=>$address_sns]);

                    //超过累积方量，则更新对账时间
                    //获取累积方量
                    $row_area = Db::name('mill_order_archives_give')
                        ->alias('g')
                        ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                        ->where([['address_sn','in',$address_sns]])
                        ->sum('a.one_area');
                    $row_area = floatval($row_area);
                    //更新对账时间
                    if($row_area >= $finance_config['pay_area_num']){
                        $rece_time = strtotime(date('Y-m-d'));
                        Db::name('mill_audit')->where(['id'=>$audit['id']])->update(['rece_time'=>$rece_time]);
                    }

                }
                //新增对账单
                if(empty($audit))$audit_id = Db::name('mill_audit')->insertGetId($add);
                else $audit_id = $audit['id'];

                //获取对账单信息
                $audit = AuditModel::fromData($audit_id);

                //获取上次剩余未结算的金额
                $prev_money = Db::name('mill_audit')->where([['id','<',$audit_id]])->order('id desc')->value('next_money');

                //发货还有剩余
                if(!empty($give_address)){
                    //应收金额
                    $rece_money = floatval($audit['sum_money']);
                    //实收金额
                    $sum_money = round($rece_money*($finance_config['pay_money_scale']/100),2);
                    //累计到下次结算的金额
                    $next_money = floatval($prev_money)+($rece_money-$sum_money);
                }
                //全部发完货
                else{
                    //应收金额
                    $rece_money = floatval($audit['sum_money'])+floatval($prev_money);
                    //实收金额
                    $sum_money = round($rece_money*($finance_config['pay_end_pay_scale']/100),2);
                    //累计到下次结算的金额
                    $next_money = $rece_money-$sum_money;
                    //生成最后一笔调账单
                    $end_finance = [
                        'create_time'           =>  time(),
                        'update_time'           =>  time(),
                        'address_time'          =>  $address_time,
                        'order_pid'             =>  $order['order_pid'],
                        'order_sn'              =>  $order['order_sn'],
                        'handle'                =>  $order['archives_handle'],
                        'audit_id'              =>  $audit_id,
                        //收款
                        'money'                 =>  $next_money,
                        'rece_money'            =>  $next_money,
                        'rece_time'             =>  $rece_time,
                    ];
                    //累计到下次结算的金额
                    $next_money = 0;
                }
                break;
            //按累积款
            //累计达到进度款_100_万元，在_5_天内对账
            case 9:
                //获取进度款，单位（万元）
                $finance_config['recon_money'] = $finance_config['recon_money']*10000;
                //更新对账日期
                $add['rece_time'] = 0;
                $rece_time = $add['rece_time'];

                //查询最新的对账单
                $audit_where = [
                    ['order_pid','=',$order['order_pid']],
                ];
                $audit = Db::name('mill_audit')->where($audit_where)->order('id desc')->find();
                //如果超过累积进度款，生成新的对账单
                if(empty($audit) || $audit['money'] >= $finance_config['recon_money'])$audit_id = Db::name('mill_audit')->insertGetId($add);
                else{
                    $audit_id = $audit['id'];
                    //更新发货单
                    $address_sns = explode(',',$audit['address_sns']);
                    $address_sns[] = $address['address_sn'];
                    $address_sns = implode(',',array_unique($address_sns));
                    Db::name('mill_audit')->where(['id'=>$audit_id])->update(['address_sns'=>$address_sns]);
                }
                //获取对账单信息
                $audit = AuditModel::fromData($audit_id);
                //如果超过累积进度款，或者已发货完，则更新对账时间
                if($audit['sum_money'] >= $finance_config['recon_money'] || empty($give_address)){
                    //更新对账时间
                    $rece_time = strtotime(date('Y-m-d'));
                    Db::name('mill_audit')->where(['id'=>$audit['id']])->update(['rece_time'=>$rece_time]);
                }

                //获取上次剩余未结算的金额
                $prev_money = Db::name('mill_audit')->where([['id','<',$audit_id]])->order('id desc')->value('next_money');
                //应收金额
                $rece_money = floatval($audit['sum_money']);
                //实收金额
                $sum_money = $rece_money + floatval($prev_money);
                //累计到下次结算的金额
                $next_money = 0;
                //发货还有剩余
                if(!empty($give_address)){
                    //实收金额
                    $sum_money = round($rece_money*($finance_config['pay_money_scale']/100),2);
                    //累计到下次结算的金额
                    $next_money = floatval($prev_money)+($rece_money-$sum_money);
                }
                break;
            //按预付款
            //甲方支付乙方_5_万元作为材料预付款，预付款在第一次结算支付时一次性扣除；
            //材料到场发票移交甲方之日起_7_个工作日付该批货物全款:；结算金额达合同量_80_%时，结算扣留_5_万元，供货完成无质量色差问题，_2_个月内把剩余货款全部付清给乙方。
            //_2023-1-20_内供货金额超过预付款的，超出部分须在_2023-1-20_前结清。
            case 10:

                //获取该工程的总款项
                $order_money = AuditModel::getFinanceSumMoney($order['order_pid']);
                //获取主调账单
                $finance = Db::name('mill_finance')->where(['order_pid'=>$order['order_pid'],'pid'=>0])->find();
                //获取剩余预付款，单位（万元）
                if(empty($finance))$advance_money = $finance_config['advance_money']*10000;
                else $advance_money = $finance['advance_money'];
                //获取质保金，单位（万元）
                if(!empty($finance['quality_money']))$quality_money = $finance['quality_money']*10000;

                //$audit_id = Db::name('mill_audit')->insertGetId($add);
                $audit_id = Db::name('mill_audit')->insertGetId($add);
                //获取对账单信息
                $audit = AuditModel::fromData($audit_id);

                //获取上次剩余未结算的金额
                $prev_money = Db::name('mill_audit')->where([['id','<',$audit_id]])->order('id desc')->value('next_money');
                //应收金额
                $rece_money = floatval($audit['sum_money']);
                //实收金额
                $sum_money = $rece_money + floatval($prev_money);
                //实收金额，优先扣除预付款
                if($advance_money > 0){
                    $sum_money -= $advance_money;
                    if($sum_money < 0){
                        $advance_money = abs($sum_money);
                        $sum_money = 0;
                    }
                    else $advance_money = 0;
                }
                /*//如果总进度款达到总工程金额80%，则扣留5万，作为质保金
                $pay_money_scale = ($audit['money']+$finance['rece_money'])/$order_money;
                if($pay_money_scale >= $finance_config['pay_money_scale'] && $quality_money == 0){
                    $quality_money = $finance_config['retention_money'];
                    $sum_money -= $quality_money;
                    //生成最后一笔质保金调账单
                    $end_finance = [
                        'create_time'           =>  time(),
                        'update_time'           =>  time(),
                        'address_time'          =>  $address_time,
                        'order_pid'             =>  $order['order_pid'],
                        'order_sn'              =>  $order['order_sn'],
                        'handle'                =>  $order['archives_handle'],
                        'audit_id'              =>  0,
                        'note'                  =>  '扣留的质保金',
                        //收款
                        'money'                 =>  $quality_money,
                        'rece_money'            =>  $quality_money,
                        'rece_time'             =>  time(),
                    ];
                }*/
                break;
        }

        if(empty($audit_id))return '';
        //更新到主调账单
        $finance = Db::name('mill_finance')->where(['order_pid'=>$order['order_pid'],'pid'=>0])->find();
        if(empty($finance)){

            $add = [
                'create_time'           =>  time(),
                'update_time'           =>  time(),
                //'address_sns'           =>  $address['address_sn'],
                'order_pid'             =>  $order['order_pid'],
                'order_sn'              =>  $order['order_sn'],
                'engineering'           =>  $order['engineering'],
                'company'               =>  $order['company'],
                'handle'                =>  $order['archives_handle'],
                //收款
                'sum_money'             =>  self::orderSumMoney($order['order_pid']),//工程总金额
                'deposit_money'         =>  $finance_money,//定金
                'late_money'            =>  $late_money,//滞纳金
                'late_time'             =>  $late_time,//滞纳金归还时间
                'rece_time'             =>  $rece_time,
            ];
            $id = Db::name('mill_finance')->insertGetId($add);
            $finance = Db::name('mill_finance')->where(['id'=>$id])->find();
        }
        //获取更新前的对账单信息
        $old_audit = Db::name('mill_audit')->where(['id'=>$audit_id])->find();
        //获取累积方量
        $old_audit['row_area'] = Db::name('mill_order_archives_give')->alias('g')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where([['address_sn','in',$old_audit['address_sns']]])->sum('a.one_area');
        $old_audit['row_area'] = floatval($old_audit['row_area']);
        //更新对账单，实收金额，应收金额，剩余未结算的金额
        Db::name('mill_audit')->where(['id'=>$audit_id])->update(['money'=>$sum_money,'rece_money'=>$rece_money,'next_money'=>$next_money,'row_area'=>$old_audit['row_area']]);
        //调账单
        //实收金额
        $inc_money = $sum_money-$old_audit['money'];//实际增加的实收金额=更新后的对账单-更新前的对账单
        Db::name('mill_finance')->where(['id'=>$finance['id']])->setInc('money',$inc_money);
        //应收金额
        $inc_rece_money = $rece_money-$old_audit['rece_money'];//实际增加的应收金额=更新后的对账单-更新前的对账单
        Db::name('mill_finance')->where(['id'=>$finance['id']])->setInc('rece_money',$inc_rece_money);

        //获取累积方量
        $row_area = Db::name('mill_order_archives_give')->alias('g')->leftJoin('mill_order_archives a','a.id=g.archives_id')->where(['g.order_pid'=>$order['order_pid']])->sum('a.one_area');
        $row_area = floatval($row_area);
        //预付金额，质保金额，最后发货时间，累积方量，预计收款时间
        $add = ['advance_money'=>$advance_money,'quality_money'=>$quality_money,'address_time'=>$address_last_time,'row_area'=>$row_area];
        if(!empty($rece_time))$add['rece_time'] = $rece_time;
        Db::name('mill_finance')->where(['id'=>$finance['id']])->update($add);
        //更新子调账单
        $finance2 = Db::name('mill_finance')->where(['audit_id'=>$audit_id])->find();
        if(empty($finance2)){

            $add = [
                'create_time'           =>  time(),
                'update_time'           =>  time(),
                'address_time'          =>  $address_time,
                'order_pid'             =>  $order['order_pid'],
                'order_sn'              =>  $order['order_sn'],
                'engineering'           =>  $order['engineering'],
                'company'               =>  $order['company'],
                'handle'                =>  $order['archives_handle'],
                'audit_id'              =>  $audit_id,
                'pid'                   =>  $finance['id'],
                'row_area'              =>  $old_audit['row_area'],
                //收款
                'money'                 =>  $sum_money,
                'rece_money'            =>  $rece_money,
                'rece_time'             =>  $rece_time,
            ];

            $id = Db::name('mill_finance')->insertGetId($add);
        }
        else{
            $add = [
                'row_area'              =>  $old_audit['row_area'],
                //收款
                'money'                 =>  $sum_money,
                'rece_money'            =>  $rece_money,
            ];
            if(!empty($rece_time))$add['rece_time'] = $rece_time;
            Db::name('mill_finance')->where(['id'=>$finance2['id']])->update($add);
        }
        //生成最后一笔调账单
        if(!empty($end_finance)){
            $end_finance['pid'] = $finance['id'];
            $end_finance['engineering'] = $order['engineering'];
            $end_finance['company'] = $order['company'];

            $id = Db::name('mill_finance')->insertGetId($end_finance);
        }

    }

    //获取该工程的应收款等信息
    public static function financeInfo($order_pid = 0){

        $order = Db::name('mill_order')->where("order_pid <> {$order_pid} and note <> ''")->order('update_time desc')->find();
        $where = [
            'order_pid'     =>  $order_pid,
            'pid'           =>  0,
        ];
        //获取总账单
        $finance = Db::name('mill_finance')->where($where)->find();

        //定金
        $data['deposit_money'] = $order['money_str'];

        //该工程的期初结余
        $data['opening_money'] = $finance['opening_money'];

        //该工程的总货款
        $data['order_money'] = $finance['sum_money'];

        //付款节点
        $data['html_config'] = '';

        //付款节点
        $data['html_config'] = $order['note'];
        //该工程的总货款
        $data['order_money'] = AuditModel::getFinanceSumMoney($order_pid);

        //该工程的总回款
        $data['receivable_money'] = Db::name('mill_finance_log')->where(['order_pid'=>$order_pid])->sum('money');
        $data['receivable_money'] = floatval($data['receivable_money']);

        //该工程的总应收款
        $data['rece_money_sum'] = $data['order_money']-$data['receivable_money']-$data['deposit_money']-$data['opening_money'];

        //该工程的已开票总金额
        $data['invoice_money'] = Db::name('mill_finance_invoice')->where(['order_pid'=>$order_pid])->sum('money');
        $data['invoice_money'] = floatval($data['invoice_money']);

        //该工程的已对账金额
        $data['audit_money'] = Db::name('mill_audit')->where(['order_pid'=>$order_pid,'status'=>2])->sum('rece_money');

        //该工程的未对账金额
        $data['audit_no_money'] = Db::name('mill_audit')->where(['order_pid'=>$order_pid])->where('status >= 0 and status < 2')->sum('rece_money');

        return $data;
    }

    //获取工程总金额
    public static function orderSumMoney($order_pid = 0){

        $sum_money = 0;
        if(empty($order_pid))return $sum_money;

        //获取已计价的工程
        $order_ids = Db::name('mill_order')->where(['order_pid'=>$order_pid,'initial_price_status'=>2])->column('id');
        if(!empty($order_ids)){
            foreach ($order_ids as $order_id){
                $finance = self::fromArchivesShow($order_id);

                if(!empty($finance['order_info']['sum_group_price']))$sum_money += $finance['order_info']['sum_group_price'];
            }
        }

        return $sum_money;

    }

}
